package com.bzyd.shiro.shiro;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.bzyd.shiro.bean.ShiroUser;
import com.bzyd.shiro.entity.Menu;
import com.bzyd.shiro.entity.Role;
import com.bzyd.shiro.entity.User;
import com.bzyd.shiro.mapper.*;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义认证方式
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    //菜单授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //当前登录的用户
        System.out.println("====授权====：" + LocalDateTime.now());
        ShiroUser shiroUser = (ShiroUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(getRoles(shiroUser.getRoles()));
        info.setStringPermissions(getPermissions(shiroUser.getMenus()));
        return info;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("====认证====：" + LocalDateTime.now());
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = new LambdaQueryChainWrapper<>(userMapper).eq(User::getUsername,username).one();
        if (user == null){
            throw new UnknownAccountException();
        }

        if (user.getStatus() != 0){
            throw new LockedAccountException();
        }

        List<Role> roles = roleMapper.findRoleByUserId(user.getId());
        List<Menu> menus = menuMapper.findMenuByRoles(roles);
        ShiroUser<User> shiroUser = new ShiroUser<>();
        shiroUser.setUserInfo(user)
                .setRoles(roles)
                .setMenus(menus);

        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());
        return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), credentialsSalt, getName());
    }

    private Set<String> getRoles(List<Role> roles){
        Set<String> set = new HashSet<>();
        if (roles != null){
            set = roles.stream().map(Role::getRolename).collect(Collectors.toSet());
        }
        return set;
    }

    private Set<String> getPermissions(List<Menu> menus){
        Set<String> set = new HashSet<>();
        if (menus != null){
            set = menus.stream().map(Menu::getPermission).collect(Collectors.toSet());
        }
        return set;
    }


}
